package com.ekuaitu.kuaitu.activity;

import android.Manifest;
import android.app.ActivityManager;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.Circle;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.ekuaitu.kuaitu.R;
import com.ekuaitu.kuaitu.api.ApiStore;
import com.ekuaitu.kuaitu.api.UrlConstant;
import com.ekuaitu.kuaitu.bean.HeartBean;
import com.ekuaitu.kuaitu.bean.OpenBikeBean;
import com.ekuaitu.kuaitu.bean.OperateBean;
import com.ekuaitu.kuaitu.bean.QueryLockBean;
import com.ekuaitu.kuaitu.bean.RedBikeHotSpotInfoBean;
import com.ekuaitu.kuaitu.bean.ResultBean;
import com.ekuaitu.kuaitu.bean.ValidateBikeBean;
import com.ekuaitu.kuaitu.ble.BleNotify;
import com.ekuaitu.kuaitu.ble.BluetoothHelper;
import com.ekuaitu.kuaitu.ble.ClientManager;
import com.ekuaitu.kuaitu.map.MarkerUtils;
import com.ekuaitu.kuaitu.map.PolylineBoundUtils;
import com.ekuaitu.kuaitu.map.SensorEventHelper;
import com.ekuaitu.kuaitu.utils.Constants;
import com.ekuaitu.kuaitu.utils.DensityUtils;
import com.ekuaitu.kuaitu.utils.IntentKey;
import com.ekuaitu.kuaitu.utils.KuaituDialog;
import com.ekuaitu.kuaitu.utils.MyApplication;
import com.ekuaitu.kuaitu.utils.NetUtils;
import com.ekuaitu.kuaitu.utils.StatusBarUtil;
import com.ekuaitu.kuaitu.utils.Toast.ToastCompat;
import com.inuker.bluetooth.library.connect.listener.BluetoothStateListener;
import com.inuker.bluetooth.library.connect.options.BleConnectOptions;
import com.inuker.bluetooth.library.connect.response.BleConnectResponse;
import com.inuker.bluetooth.library.connect.response.BleWriteResponse;
import com.inuker.bluetooth.library.model.BleGattProfile;
import com.inuker.bluetooth.library.search.SearchRequest;
import com.inuker.bluetooth.library.search.SearchResult;
import com.inuker.bluetooth.library.search.response.SearchResponse;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.inuker.bluetooth.library.Constants.REQUEST_FAILED;
import static com.inuker.bluetooth.library.Constants.REQUEST_SUCCESS;

public class BikeRedTaskActivity extends AppCompatActivity implements AMapLocationListener, AMap.OnMarkerClickListener, AMap.InfoWindowAdapter, BleNotify.BlueNotifyCallBack {

    @BindView(R.id.redtask_ivReturn)
    ImageView redtaskIvReturn;
    @BindView(R.id.redtask_toolbar)
    Toolbar redtaskToolbar;
    @BindView(R.id.redtask_tvBikenum)
    TextView redtaskTvBikenum;
    @BindView(R.id.redtask_ivRed)
    ImageView redtaskIvRed;
    @BindView(R.id.redtask_rl)
    RelativeLayout redtaskRl;
    @BindView(R.id.redtask_receive)
    TextView redtaskReceive;
    @BindView(R.id.redtask_ll)
    LinearLayout redtaskLl;
    @BindView(R.id.activity_bike_red_task)
    RelativeLayout activityBikeRedTask;
    @BindView(R.id.progressBar)
    LinearLayout progressBar;
    @BindView(R.id.imageView_refresh)
    ImageView imageView_refresh;


    private MapView mapView;
    private AMap aMap;
    private AMapLocationClient mLocationClient;
    private AMapLocationClientOption mLocationOption;
    private MarkerUtils markerUtils;
    private Marker locationMarker;
    private Circle mCircle;
    private PolylineBoundUtils polylineBoundUtils;
    private SensorEventHelper mSensorHelper;
    private LatLng curPosition;
    private Context mContext = this;
    private Boolean isFirstLocation = true;
    private List<Marker> brandMarkerList = new ArrayList<>();
    private String scanedRedBikeLicense;
    private String bikeId;
    private int lockType;
    private LatLng redBikePosition;
    private View infoWindow = null;
    private AMapLocation aMapLocation;
    private String orderId;
    private int queryCount = 0;
    private CountDownTimer timerQuery;
    private ProgressDialog pdSearch;
    private String btMac;
    public static final UUID serverUUID = UUID.fromString("0000fee7-0000-1000-8000-00805f9b34fb");
    public static final UUID readDataUUID = UUID.fromString("000036f6-0000-1000-8000-00805f9b34fb");
    public static final UUID writeDataUUID = UUID.fromString("000036f5-0000-1000-8000-00805f9b34fb");
    byte[] btToken = new byte[4];
    byte[] loadPwd = new byte[6];
    byte[] loadKey = new byte[16];
    private int caozuo = 0;
    private int power;
    private boolean isOpenLock = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bike_red_task);
        ButterKnife.bind(this);
        mapView = (MapView) findViewById(R.id.redtask_map);
        mapView.onCreate(savedInstanceState);
        initData();
        initView();
    }


    private void initView() {
        StatusBarUtil.setColor(this, getResources().getColor(R.color.colorPrimary), 0, false);
        redtaskTvBikenum.setText(scanedRedBikeLicense);
        initMap();
        getLocationPermission();
    }

    private void initData() {
        Intent intent = getIntent();
        scanedRedBikeLicense = intent.getStringExtra("scanedRedBikeLicense");
        bikeId = intent.getStringExtra(IntentKey.INTENT_BIKE_ID);
        lockType = intent.getIntExtra(IntentKey.INTENT_LOCK_TYPE, 0);
        redBikePosition = new LatLng(intent.getDoubleExtra("redBikeLatitude", 0), intent.getDoubleExtra("redBikeLongitude", 0));
    }

    private void getLocationPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED ||
                    ContextCompat.checkSelfPermission(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        Constants.READ_LOCATION_PERMISSION_REQUEST);
            } else {
                startLocation();
            }
        } else {
            startLocation();
        }
    }

    private void startLocation() {
        progressBar.setVisibility(View.VISIBLE);
        mLocationClient.startLocation();
    }

    public void initMap() {
        if (aMap == null) {
            aMap = mapView.getMap();
            //设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
            aMap.setMyLocationEnabled(false);
            aMap.setMapType(AMap.MAP_TYPE_NAVI);
            //设置点击marker事件监听器
            aMap.setOnMarkerClickListener(this);
            aMap.setInfoWindowAdapter(this);// 设置自定义InfoWindow样式
            UiSettings uiSettings = aMap.getUiSettings();
            //设置地图交互
            uiSettings.setMyLocationButtonEnabled(false);
            uiSettings.setScaleControlsEnabled(false);
            uiSettings.setRotateGesturesEnabled(false);
            uiSettings.setZoomControlsEnabled(false);
            uiSettings.setScrollGesturesEnabled(true);
            uiSettings.setZoomGesturesEnabled(true);
            uiSettings.setTiltGesturesEnabled(false);

            //设置定位的参数
            if (mLocationClient == null) {
                mLocationClient = new AMapLocationClient(getApplicationContext());
                mLocationOption = new AMapLocationClientOption();
                //设置定位监听
                mLocationClient.setLocationListener(this);
                //设置为高精度定位模式
                mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
                mLocationOption.setInterval(2000);
                //设置定位参数
                mLocationClient.setLocationOption(mLocationOption);
            }

            markerUtils = new MarkerUtils(mContext, aMap);
            polylineBoundUtils = new PolylineBoundUtils(aMap);

            aMap.setOnMapClickListener(new AMap.OnMapClickListener() {
                @Override
                public void onMapClick(LatLng latLng) {
                    //backPress(false);
                }
            });

            aMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
                @Override
                public void onCameraChange(CameraPosition cameraPosition) {
                }

                @Override
                public void onCameraChangeFinish(CameraPosition cameraPosition) {
                }
            });
        }
    }

    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (amapLocation != null && amapLocation.getErrorCode() == 0) {
            this.aMapLocation = amapLocation;
            progressBar.setVisibility(View.GONE);
            // 更新定位
            curPosition = new LatLng(amapLocation.getLatitude(), amapLocation.getLongitude());
            if (isFirstLocation) {         //首次定位
                isFirstLocation = false;
                aMap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(curPosition, 16, 0, 0)));
                MyApplication.getInstance().setAreaCode(amapLocation.getCityCode());
                locationMarker = markerUtils.addLocationIcon(curPosition);
                mCircle = polylineBoundUtils.addCircle(curPosition, amapLocation.getAccuracy());//添加定位精度圆
                locationMarker.setClickable(false);
                mSensorHelper.setCurrentMarker(locationMarker);
                //获取任务单车的信息
                getRedBikeHotSpotInfo();

            } else {
                locationMarker.setPosition(curPosition);
                mCircle.setCenter(curPosition);
                mCircle.setRadius(amapLocation.getAccuracy());
            }

        } else {
            if (isFirstLocation) {
                mLocationClient.startLocation();
            } else {
                String errText = "获取定位信息失败...";
                ToastCompat.makeText(mContext, errText, Toast.LENGTH_SHORT).show();
            }
        }

    }


    private void getRedBikeHotSpotInfo() {
        progressBar.setVisibility(View.VISIBLE);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).getRedBikeHotSpotInfo(MyApplication.getInstance().getRequestFieldMap(), redBikePosition.latitude + "", redBikePosition.longitude + "").enqueue(new Callback<RedBikeHotSpotInfoBean>() {
            @Override
            public void onResponse(Call<RedBikeHotSpotInfoBean> call, Response<RedBikeHotSpotInfoBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        progressBar.setVisibility(View.GONE);
                        //绘制任务车的地图UI
                        drawRedBikeMap(response.body().getAttachment());
                    } else {
                        progressBar.setVisibility(View.GONE);
                        ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<RedBikeHotSpotInfoBean> call, Throwable t) {
                progressBar.setVisibility(View.GONE);
                ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_LONG).show();
                Log.i("netError", "040" + t);
            }
        });
    }

    private void drawRedBikeMap(final List<RedBikeHotSpotInfoBean.AttachmentBean> rebBikeInfo) {
        //缩放地图
        LatLngBounds.Builder b = LatLngBounds.builder();
        if (curPosition != null) {
            b.include(curPosition);
        }
        //画热区和商家
        for (int i = 0; i < rebBikeInfo.size(); i++) {
            b.include(new LatLng(rebBikeInfo.get(i).getCenterLatitude(), rebBikeInfo.get(i).getCenterLongitude()));
            List<LatLng> redBikeBound = new ArrayList<>();
            for (RedBikeHotSpotInfoBean.AttachmentBean.PointListBean redBikeBoundInfo : rebBikeInfo.get(i).getPointList()) {
                redBikeBound.add(new LatLng(redBikeBoundInfo.getLatitude(), redBikeBoundInfo.getLongitude()));
            }
            polylineBoundUtils.addBoundAndCoverToMap(redBikeBound);
            if ((rebBikeInfo.get(i).getBusinessName() != null && !rebBikeInfo.get(i).getBusinessName().equals(""))) {
                new MarkerUtils(mContext, aMap).addBrandMarkerToMap(rebBikeInfo.get(i).getBusinessLatitude(), rebBikeInfo.get(i).getBusinessLongitude(),
                        rebBikeInfo.get(i).getBusinessName(), rebBikeInfo.get(i).getBusinessImg(), new MarkerUtils.OnBrandMarkerAddedListener() {
                            @Override
                            public void onBrandMarkerAdded(Marker marker) {
                                //商家Marker，加入到list中，后续用来从地图上清除这些marker
                                brandMarkerList.add(marker);
                            }
                        });
            }
        }
        aMap.animateCamera(CameraUpdateFactory.newLatLngBoundsRect(
                b.build(),
                DensityUtils.dp2px(mContext, 50), DensityUtils.dp2px(mContext, 50), DensityUtils.dp2px(mContext, 50), DensityUtils.dp2px(mContext, 50)),
                400,
                null);
    }

    //clickMarker
    @Override
    public boolean onMarkerClick(Marker marker) {
        marker.showInfoWindow();
        return false;
    }

    @OnClick({R.id.redtask_ivReturn, R.id.redtask_rl, R.id.redtask_receive, R.id.imageView_refresh})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.redtask_ivReturn:
                finish();
                break;
            case R.id.redtask_rl:
                Intent intent = new Intent(mContext, WebViewActivity.class);
                intent.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "任务攻略");
                intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlConstant.Request.REDPACKAGE_DETAIL);
                startActivity(intent);
                break;
            case R.id.redtask_receive:
                //  开锁
                pdSearch = new ProgressDialog(BikeRedTaskActivity.this);
                pdSearch.setMessage("正在联系单车，请耐心等待...");
                pdSearch.setCancelable(false);
                pdSearch.show();
                if (curPosition != null) {
                    openBikePreValidateBike(scanedRedBikeLicense);
                } else {
                    ToastCompat.makeText(mContext, "正在获取您的位置信息...", Toast.LENGTH_LONG).setGravity(Gravity.CENTER, 0, 0).show();
                }
                break;
/*            case R.id.redtask_no:
                if (curPosition != null) {
                    sendLog();
                    finish();
                } else {
                    ToastCompat.makeText(mContext, "正在获取您的位置信息...", Toast.LENGTH_LONG).setGravity(Gravity.CENTER, 0, 0).show();
                }
                break;*/
            case R.id.imageView_refresh:
                aMap.animateCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(curPosition, 16, 0, 0)), 700, null);
                break;
        }
    }



    private void openBikePreValidateBike(final String scanedBikeLicense) {
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).validateBike(MyApplication.getInstance().getRequestFieldMap(), scanedBikeLicense, curPosition.latitude + "", curPosition.longitude + "")
                .enqueue(new Callback<ValidateBikeBean>() {
                    @Override
                    public void onResponse(Call<ValidateBikeBean> call, Response<ValidateBikeBean> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            if (response.body().getStatus() == 200) {
                                lockType = response.body().getAttachment().getBikeInfo().getLockType();
                                bikeId = response.body().getAttachment().getBikeInfo().getBikeId();
                                if (response.body().getAttachment().getBikeInfo().getIsRedPackage() == 1) {          //任务车继续开锁流程
                                    if (lockType == 1) {
                                        openBikeGpsBike();
                                    } else if (lockType == 2 || lockType == 3 || lockType == 4) {
                                        isOpenLock = true;
                                        requestBTBikeInfo(bikeId);
                                    }
                                } else if (response.body().getAttachment().getBikeInfo().getIsRedPackage() == 0) {  //已经不是任务车了提示
                                    if (pdSearch != null) {
                                        pdSearch.dismiss();
                                    }
                                    ToastCompat.makeText(mContext, "该单车已经不是任务车了", Toast.LENGTH_LONG).setGravity(Gravity.CENTER, 0, 0).show();
                                }

                            } else {
                                if (pdSearch != null) {
                                    pdSearch.dismiss();
                                }
                                ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_LONG).setGravity(Gravity.CENTER, 0, 0).show();
                                commitBikeLogFailed(response.body().getStatus(), response.body().getMessage());
                            }
                        } else {
                            if (pdSearch != null) {
                                pdSearch.dismiss();
                            }
                            ToastCompat.makeText(mContext, getResources().getString(R.string.serverError), Toast.LENGTH_LONG).setGravity(Gravity.CENTER, 0, 0).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<ValidateBikeBean> call, Throwable t) {
                        if (pdSearch != null) {
                            pdSearch.dismiss();
                        }
                        ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_LONG).setGravity(Gravity.CENTER, 0, 0).show();
                    }
                });
    }

    //心跳计时
    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    progressBar.setVisibility(View.VISIBLE);
                    break;
                case 2:
                    progressBar.setVisibility(View.GONE);
                    break;
            }
            super.handleMessage(msg);
        }
    };

    //获取蓝牙锁信息，之后开锁
    private void requestBTBikeInfo(String bikeId) {
        commitBikeLogPre();
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).requestBTBikeInfo(MyApplication.getInstance().getRequestFieldMap(), bikeId, "0")
                .enqueue(new Callback<QueryLockBean>() {
                    @Override
                    public void onResponse(Call<QueryLockBean> call, final Response<QueryLockBean> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            if (response.body().getStatus() == 200) {
                                btMac = response.body().getAttachment().getBikeMachineUnique();
                                String key = response.body().getAttachment().getBikeMachineKey();
                                String pwd = response.body().getAttachment().getBikeMachinePassword();
                                String[] KEY = key.split(",");
                                String[] PWD = pwd.split(",");
                                for (int i = 0; i < 16; i++) {
                                    loadKey[i] = Byte.parseByte(KEY[i]);
                                }
                                for (int j = 0; j < 6; j++) {
                                    loadPwd[j] = Byte.parseByte(PWD[j]);
                                }
                                if (ClientManager.getClient().isBluetoothOpened()) {
                                    int status = ClientManager.getClient().getConnectStatus(btMac);
                                    Log.i("redOpenResult", "firstscan" + status + "");
                                    if (status == 2) {
                                        caozuo = 0;//开锁
                                        btToken = MyApplication.btToken;
                                        byte[] openLock = {0x05, 0x01, 0x06, loadPwd[0], loadPwd[1], loadPwd[2], loadPwd[3], loadPwd[4], loadPwd[5], btToken[0], btToken[1], btToken[2], btToken[3], 0x00, 0x00, 0x00};
                                        Log.i("redOpenResult", "openlock" + Arrays.toString(openLock));
                                        sendData(openLock, btMac);
                                    } else {
                                        searchDevice();
                                    }

                                } else {
                                    ClientManager.getClient().registerBluetoothStateListener(mBluetoothStateListener);
                                    ClientManager.getClient().openBluetooth();
                                }
                            } else {
                                if (pdSearch != null) {
                                    pdSearch.dismiss();
                                }
                                ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_LONG).setGravity(Gravity.CENTER, 0, 0).show();
                            }
                        } else {
                            if (pdSearch != null) {
                                pdSearch.dismiss();
                            }
                            ToastCompat.makeText(mContext, getResources().getString(R.string.serverError), Toast.LENGTH_LONG).setGravity(Gravity.CENTER, 0, 0).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<QueryLockBean> call, Throwable t) {
                        if (pdSearch != null) {
                            pdSearch.dismiss();
                        }
                        ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_LONG).setGravity(Gravity.CENTER, 0, 0).show();
                    }
                });

    }

    //验证完单车可用后请求开锁
    private void requestOpenBtBike() {
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).requestOpenBtBike(MyApplication.getInstance().getRequestFieldMap(), bikeId, lockType + "", power + "", curPosition.longitude + "", curPosition.latitude + "")
                .enqueue(new Callback<OpenBikeBean>() {
                    @Override
                    public void onResponse(Call<OpenBikeBean> call, final Response<OpenBikeBean> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            if (response.body().getStatus() == 200) {
                                orderId = response.body().getAttachment().getOrderModel().getId();
                                sendHeat();
                                caozuo = 0;
                                byte[] getToken = {0x06, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
                                sendData(getToken, btMac);
                            } else {
                                if (pdSearch != null) {
                                    pdSearch.dismiss();
                                }
                                ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_LONG).setGravity(Gravity.CENTER, 0, 0).show();
                            }
                        } else {
                            if (pdSearch != null) {
                                pdSearch.dismiss();
                            }
                            ToastCompat.makeText(mContext, getResources().getString(R.string.serverError), Toast.LENGTH_LONG).setGravity(Gravity.CENTER, 0, 0).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<OpenBikeBean> call, Throwable t) {
                        if (pdSearch != null) {
                            pdSearch.dismiss();
                        }
                        ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_LONG).setGravity(Gravity.CENTER, 0, 0).show();
                    }
                });
    }

    //蓝牙打开结果
    private final BluetoothStateListener mBluetoothStateListener = new BluetoothStateListener() {
        @Override
        public void onBluetoothStateChanged(boolean openOrClosed) {
            if (isForeground(mContext, "com.ekuaitu.kuaitu.activity.BikeRedTaskActivity")) {
                if (openOrClosed) {
                    handler.sendEmptyMessage(1);
                    searchDevice();
                } else {
                    if (isOpenLock) {
                        isOpenLock = false;
                        if (openOrClosed) {
                            handler.sendEmptyMessage(1);
                            searchDevice();
                        } else {
                            progressBar.setVisibility(View.GONE);
                        }
                    }
                }
            }
        }
    };

    //搜索蓝牙设备
    private void searchDevice() {
        SearchRequest request = new SearchRequest.Builder().searchBluetoothLeDevice(15000, 1).build();
        ClientManager.getClient().search(request, mSearchResponse);
    }


    //蓝牙设备搜索结果
    private final SearchResponse mSearchResponse = new SearchResponse() {
        @Override
        public void onSearchStarted() {

        }

        @Override
        public void onDeviceFounded(SearchResult device) {
            if (device.scanRecord[5] == 0x01 && device.scanRecord[6] == 0x02) {
                if (device.getAddress().equals(btMac)) {
                    ClientManager.getClient().stopSearch();
                    power = device.scanRecord[14];
                    MyApplication.power = power;
                    connectDevice(btMac);
                }
            }
        }

        @Override
        public void onSearchStopped() {
            commitBikeLogFailed(0, "未扫描到该单车，请您将手机靠近车锁再试");
            if (pdSearch != null) {
                pdSearch.dismiss();
            }
            final KuaituDialog kuaituDialog = new KuaituDialog(BikeRedTaskActivity.this);
            kuaituDialog.setTitle(getString(R.string.dialogTitle));
            kuaituDialog.setMessage("未扫描到该单车，请您将手机靠近车锁再试");
            kuaituDialog.setYesOnclickListener("确定", new KuaituDialog.onYesOnclickListener() {
                @Override
                public void onYesClick() {
                    kuaituDialog.dismiss();
                }
            });
            kuaituDialog.setNoOnclickListener("取消", new KuaituDialog.onNoOnclickListener() {
                @Override
                public void onNoClick() {

                    kuaituDialog.dismiss();
                }
            });
            kuaituDialog.setCancelable(false);
            kuaituDialog.show();
        }

        @Override
        public void onSearchCanceled() {
        }
    };

    private void connectDevice(final String mac) {
        BleConnectOptions options = new BleConnectOptions.Builder()
                .setConnectRetry(1)
                .setConnectTimeout(10000)
                .setServiceDiscoverRetry(2)
                .setServiceDiscoverTimeout(7000)
                .build();
        //发起连接
        ClientManager.getClient().connect(mac, options, new BleConnectResponse() {
            @Override
            public void onResponse(int code, BleGattProfile profile) {
                if (code == REQUEST_SUCCESS) {
                    BleNotify.getInstance().setBleNotifyCallBack(BikeRedTaskActivity.this);
                    ClientManager.getClient().notify(mac, serverUUID, readDataUUID, BleNotify.getInstance().getBleNotifyResponse());
                    Log.i("redOpenResult", "连接成功" + mac);
                    requestOpenBtBike();
                } else if (code == REQUEST_FAILED) {
                    commitBikeLogFailed(0, "连接蓝牙失败");
                    if (pdSearch != null) {
                        pdSearch.dismiss();
                    }
                    final KuaituDialog kuaituDialog = new KuaituDialog(mContext);
                    kuaituDialog.setTitle(getString(R.string.dialogTitle));
                    kuaituDialog.setMessage("对不起！未能连接到这个单车，您可以再次尝试");
                    kuaituDialog.setYesOnclickListener("确认", new KuaituDialog.onYesOnclickListener() {
                        @Override
                        public void onYesClick() {
                            ClientManager.getClient().closeBluetooth();
                            kuaituDialog.dismiss();
                        }
                    });
                    kuaituDialog.setNoOnclickListener("取消", new KuaituDialog.onNoOnclickListener() {
                        @Override
                        public void onNoClick() {
                            kuaituDialog.dismiss();
                            ClientManager.getClient().closeBluetooth();
                        }
                    });
                    kuaituDialog.show();
                } else {
                    progressBar.setVisibility(View.GONE);
                }
            }
        });

    }

    private void sendData(byte[] data, final String mac) {
        byte[] miwen = Encrypt(data, loadKey);

        //发送命令
        ClientManager.getClient().write(mac, serverUUID, writeDataUUID, miwen, new BleWriteResponse() {
            @Override
            public void onResponse(int code) {
                if (code == REQUEST_SUCCESS) {

                }
            }
        });
    }

    //GPS锁开锁
    private void openBikeGpsBike() {
        commitBikeLogPre();
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).openBike(MyApplication.getInstance().getRequestFieldMap(), bikeId, "1", curPosition.latitude + "", curPosition.longitude + "").enqueue(new Callback<OpenBikeBean>() {
            @Override
            public void onResponse(Call<OpenBikeBean> call, Response<OpenBikeBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        orderId = response.body().getAttachment().getOrderModel().getId();
                        sendHeat();
                        queryCount = 0;
                        queryLockInfo();
                        commitBikeLogSuccess();
                    } else {
                        if (pdSearch != null) {
                            pdSearch.dismiss();
                        }
                        ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_LONG).setGravity(Gravity.CENTER, 0, 0).show();
                        commitBikeLogFailed(response.body().getStatus(), response.body().getMessage());
                    }
                } else {
                    if (pdSearch != null) {
                        pdSearch.dismiss();
                    }
                    ToastCompat.makeText(mContext, getResources().getString(R.string.serverError), Toast.LENGTH_LONG).setGravity(Gravity.CENTER, 0, 0).show();
                }
            }

            @Override
            public void onFailure(Call<OpenBikeBean> call, Throwable t) {
                if (pdSearch != null) {
                    pdSearch.dismiss();
                }
                ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_LONG).setGravity(Gravity.CENTER, 0, 0).show();

            }
        });
    }

    //轮询Gps锁开锁结果
    private void queryLockInfo() {
        if (queryCount < 3 && queryCount >= 0) {
            String isSelect;
            if (queryCount == 1) {
                isSelect = "1";
            } else {
                isSelect = "0";
            }
            ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).queryLockInfo(MyApplication.getInstance().getRequestFieldMap(), bikeId, isSelect).enqueue(new Callback<QueryLockBean>() {
                @Override
                public void onResponse(Call<QueryLockBean> call, Response<QueryLockBean> response) {
                    if (response.isSuccessful() && response.body() != null) {
                        if (response.body().getStatus() == 200) {
                            if (response.body().getAttachment().getLockstatus() == 1) {
                                if (pdSearch != null) {
                                    pdSearch.dismiss();
                                }
                                queryCount = -1;
                                Intent intent = new Intent();
                                intent.putExtra(IntentKey.INTENT_ORDER_ID, orderId);
                                intent.setClass(mContext, BikeInUseRedActivity.class);
                                startActivity(intent);
                                finish();
                            } else {
                                queryCount++;
                                if (timerQuery != null) {
                                    timerQuery.cancel();
                                    timerQuery = null;
                                }
                                timerQuery = new CountDownTimer(5000, 1000) {
                                    @Override
                                    public void onTick(long l) {
                                        if (pdSearch != null) {
                                            pdSearch.show();
                                        }
                                    }

                                    @Override
                                    public void onFinish() {
                                        queryLockInfo();
                                    }
                                };
                                timerQuery.start();
                            }
                        } else {
                            if (pdSearch != null) {
                                pdSearch.dismiss();
                            }
                            ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                }

                @Override
                public void onFailure(Call<QueryLockBean> call, Throwable t) {
                    if (pdSearch != null) {
                        pdSearch.dismiss();
                    }
                    ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_LONG).setGravity(Gravity.CENTER, 0, 0).show();

                }
            });
        } else {
            if (pdSearch != null) {
                pdSearch.dismiss();
            }
            final KuaituDialog kuaituDialog = new KuaituDialog(BikeRedTaskActivity.this);
            kuaituDialog.setTitle(getString(R.string.dialogTitle));
            kuaituDialog.setMessage("网络不稳定，重新尝试打开车锁");
            kuaituDialog.setYesOnclickListener("确定", new KuaituDialog.onYesOnclickListener() {
                @Override
                public void onYesClick() {
                    queryCount = 0;
                    if (pdSearch != null) {
                        pdSearch.show();
                    }
                    queryLockInfo();
                    kuaituDialog.dismiss();
                }
            });
            kuaituDialog.setNoOnclickListener("取消", new KuaituDialog.onNoOnclickListener() {
                @Override
                public void onNoClick() {
                    kuaituDialog.dismiss();
                }
            });
            kuaituDialog.setCancelable(false);
            kuaituDialog.show();
        }
    }


    //开锁后并获取电量后回传服务器锁信息
    private void sendBTLockInfo(final int lockStatus, int operationStatus) {
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).sendBTLockInfo(MyApplication.getInstance().getRequestFieldMap(), bikeId, lockType + "", power + "",
                curPosition.longitude + "", curPosition.latitude + "", lockStatus + "", operationStatus + "", orderId, "1")
                .enqueue(new Callback<OperateBean>() {
                    @Override
                    public void onResponse(Call<OperateBean> call, final Response<OperateBean> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            if (pdSearch != null) {
                                pdSearch.dismiss();
                            }
                            if (response.body().getStatus() == 200) {
                                if (lockStatus == 1) {
                                    Intent intent = new Intent();
                                    intent.putExtra(IntentKey.INTENT_ORDER_ID, orderId);
                                    intent.setClass(mContext, BikeInUseRedActivity.class);
                                    startActivity(intent);
                                    finish();
                                }
                            } else {
                                ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            if (pdSearch != null) {
                                pdSearch.dismiss();
                            }
                            ToastCompat.makeText(mContext, getResources().getString(R.string.serverError), Toast.LENGTH_LONG).setGravity(Gravity.CENTER, 0, 0).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<OperateBean> call, Throwable t) {
                        if (pdSearch != null) {
                            pdSearch.dismiss();
                        }
                        ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_LONG).setGravity(Gravity.CENTER, 0, 0).show();
                    }
                });
    }

    @Override
    protected void onResume() {
        super.onResume();
        aMap.setMapType(AMap.MAP_TYPE_NAVI);
        mapView.onResume();

        if (!isFirstLocation) {
            mLocationClient.startLocation();
        }
        initSensor();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mLocationClient.stopLocation();
        if (mSensorHelper != null) {
            mSensorHelper.unRegisterSensorListener();
            mSensorHelper.setCurrentMarker(null);
            mSensorHelper = null;
        }
        mapView.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        if (null != mLocationClient) {
            mLocationClient.onDestroy();
        }
        if (timerQuery != null) {
            timerQuery.cancel();
            timerQuery = null;
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }


    private void initSensor() {
        if (mSensorHelper != null) {
            mSensorHelper.registerSensorListener();
        } else {
            mSensorHelper = new SensorEventHelper(this);
            mSensorHelper.registerSensorListener();
            if (mSensorHelper.getCurrentMarker() == null && locationMarker != null) {
                mSensorHelper.setCurrentMarker(locationMarker);
            }
        }
    }

    @Override
    public View getInfoWindow(Marker marker) {
        if (infoWindow == null) {
            infoWindow = LayoutInflater.from(mContext).inflate(R.layout.info_window, null);
        }
        render(marker, infoWindow);
        return infoWindow;
    }

    @Override
    public View getInfoContents(Marker marker) {
        return null;
    }

    public void render(Marker marker, View view) {
        TextView tv_distance = (TextView) view.findViewById(R.id.info_window_distance);
        tv_distance.setText(marker.getTitle());

    }

    private void sendHeat() {
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL_PHP).sendHeart(MyApplication.getInstance().getRequestFieldMap(), orderId, bikeId, curPosition.longitude + "", curPosition.latitude + "", lockType + "", "0").enqueue(new Callback<HeartBean>() {
            @Override
            public void onResponse(Call<HeartBean> call, Response<HeartBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getErrorCode() == 0) {
                        Log.i("heart", "heart");
                    } else {
                        ToastCompat.makeText(mContext, response.body().getMsg(), Toast.LENGTH_LONG).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<HeartBean> call, Throwable t) {
                ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_LONG).show();
            }
        });
    }

    //bike-APP端操作日志记录 操作前
    private void commitBikeLogPre() {
        NetUtils.commitBikeLog(mContext, aMapLocation, bikeId, scanedRedBikeLicense, (lockType == -1) ? "" : lockType + "", orderId, "", "1", "1", "0", "", "");
    }

    //bike-APP端操作日志记录 操作成功
    private void commitBikeLogSuccess() {
        NetUtils.commitBikeLog(mContext, aMapLocation, bikeId, scanedRedBikeLicense, (lockType == -1) ? "" : lockType + "", orderId, "", "1", "2", "0", "200", "");
    }

    //bike-APP端操作日志记录 操失败
    private void commitBikeLogFailed(int errorcode, String errormsg) {
        NetUtils.commitBikeLog(mContext, aMapLocation, bikeId, scanedRedBikeLicense, (lockType == -1) ? "" : lockType + "", orderId, "", "1", "3", "1", errorcode + "", errormsg);
    }

    //判断页面是否在前台
    public static boolean isForeground(Context context, String className) {
        if (context == null || TextUtils.isEmpty(className)) {
            return false;
        }
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
        if (list != null && list.size() > 0) {
            ComponentName cpn = list.get(0).topActivity;
            if (className.equals(cpn.getClassName())) {
                return true;
            }
        }
        return false;
    }


    // 加密
    public byte[] Encrypt(byte[] sSrc, byte[] sKey) {
        try {
            SecretKeySpec skeySpec = new SecretKeySpec(sKey, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");//"算法/模式/补码方式"
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] encrypted = cipher.doFinal(sSrc);
            return encrypted;//此处使用BASE64做转码功能，同时能起到2次加密的作用。
        } catch (Exception ex) {
            return null;
        }
    }

    // 解密
    public byte[] decrypt(byte[] sSrc, byte[] sKey) {
        try {
            SecretKeySpec skeySpec = new SecretKeySpec(sKey, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            byte[] dncrypted = cipher.doFinal(sSrc);
            return dncrypted;
        } catch (Exception ex) {
            return null;
        }
    }

    @Override
    public void onNotify(UUID service, UUID character, byte[] value) {
        byte[] x = new byte[16];
        System.arraycopy(value, 0, x, 0, 16);
        byte[] mingwen = decrypt(x, loadKey);
        if (mingwen != null && mingwen.length == 16) {
            Log.i("mingwenRedTask", Arrays.toString(mingwen));
            if (mingwen != null && mingwen.length == 16) {
                Log.i("mingwenmingwenRTToken", Arrays.toString(mingwen));
                if (mingwen[0] == 0x06 && mingwen[1] == 0x02) {
                    btToken[0] = mingwen[3];
                    btToken[1] = mingwen[4];
                    btToken[2] = mingwen[5];
                    btToken[3] = mingwen[6];
                    MyApplication.btToken = btToken;
                    BluetoothHelper.getInstance().setConnectToken(btToken);
                    if (caozuo == 0) {
                        byte[] openLock = {0x05, 0x01, 0x06, loadPwd[0], loadPwd[1], loadPwd[2], loadPwd[3], loadPwd[4], loadPwd[5], btToken[0], btToken[1], btToken[2], btToken[3], 0x00, 0x00, 0x00};
                        sendData(openLock, btMac);
                    }

                } else if (mingwen[0] == 0x05 && mingwen[1] == 0x02) {
                    //开锁成功
                    if (mingwen[3] == 0x00) {
                        sendBTLockInfo(1, 1);
                        commitBikeLogSuccess();
                    } else if (mingwen[3] == 0x01) {
                        sendBTLockInfo(0, 0);
                        if (pdSearch != null) {
                            pdSearch.dismiss();
                        }
                        ClientManager.getClient().disconnect(btMac);
                        final KuaituDialog kuaituDialog = new KuaituDialog(BikeRedTaskActivity.this);
                        kuaituDialog.setTitle(getString(R.string.dialogTitle));
                        kuaituDialog.setMessage("开锁失败，请联系客服");
                        kuaituDialog.setYesOnclickListener("确定", new KuaituDialog.onYesOnclickListener() {
                            @Override
                            public void onYesClick() {
                                kuaituDialog.dismiss();

                            }
                        });
                        kuaituDialog.setNoOnclickListener("取消", new KuaituDialog.onNoOnclickListener() {
                            @Override
                            public void onNoClick() {
                                kuaituDialog.dismiss();
                            }
                        });
                        kuaituDialog.setCancelable(false);
                        kuaituDialog.show();
                        commitBikeLogFailed(0, "蓝牙开锁失败");
                    }
                }
            }
        }
    }

}
